<script setup lang="tsx">
import { NButton, NPopconfirm } from 'naive-ui';
import { usePagination } from '@sa/alova/client';
import { computed, reactive } from 'vue';
import { batchDelCodeDb, deleteCodeDb, paginateCodeDb } from '@/service/api/dev/code';
import { $t } from '@/locales';
import { useAppStore } from '@/store/modules/app';
import useCheckedColumns from '@/hooks/common/table/table-columns';
import useTableOperate from '@/hooks/common/table/table-operate';
import CodeDbSearch from './modules/code-db-search.vue';
import CodeDbDrawer from './modules/code-db-drawer.vue';

const appStore = useAppStore();

const searchParams = reactive({
  id: null,
  name: null,
  url: null,
  username: null,
  password: null,
  creator: null,
  createTime: null,
  updater: null,
  updateTime: null
});

const { loading, data, page, pageSize, pageCount, refresh, send, remove } = usePagination(
  (p, sz) =>
    paginateCodeDb({
      ...searchParams,
      pageNumber: p,
      pageSize: sz
    }),
  {
    data: ({ records }) => records,
    total: ({ total }) => total,
    watchingStates: [searchParams],
    debounce: [500]
  }
);
const searchPaginate = (newPage = 1) => {
  page.value = newPage;
  send(page.value, pageSize.value);
};

const {
  drawerVisible,
  operateType,
  editingData,
  handleAdd,
  handleEdit,
  handleDelete,
  handleBatchDelete,
  checkedRowKeys,
  deleting
} = useTableOperate(data, {
  async delete(row) {
    await deleteCodeDb({ id: row.id });
    remove(row);
  },
  async batchDelete(rows) {
    await batchDelCodeDb({ ids: rows.map(row => row.id) });
    remove(...rows);
  }
});

function edit(id: number) {
  handleEdit(id);
}

const { columnChecks, columns } = useCheckedColumns<typeof paginateCodeDb>(() => [
  {
    type: 'selection',
    align: 'center',
    width: 48
  },
  {
    key: 'name',
    title: '名称',
    align: 'center',
    width: 100
  },
  {
    key: 'url',
    title: '连接',
    align: 'center',
    width: 100
  },
  {
    key: 'username',
    title: '用户名',
    align: 'center',
    width: 100
  },
  {
    key: 'password',
    title: '密码',
    align: 'center',
    width: 100
  },
  {
    key: 'operate',
    title: $t('common.operate'),
    align: 'center',
    width: 130,
    fixed: 'right',
    render: row => (
      <div class="flex-center gap-8px">
        <NButton type="primary" ghost size="small" onClick={() => edit(row.id as number)}>
          {$t('common.edit')}
        </NButton>
        <NPopconfirm
          onPositiveClick={() => handleDelete(row.id)}
          positiveButtonProps={{
            loading: deleting.value
          }}
        >
          {{
            default: () => $t('common.confirmDelete'),
            trigger: () => (
              <NButton type="error" ghost size="small">
                {$t('common.delete')}
              </NButton>
            )
          }}
        </NPopconfirm>
      </div>
    )
  }
]);

const paginationConfig = computed(() => ({
  page: page.value,
  pageSize: pageSize.value,
  showSizePicker: true,
  pageCount: pageCount.value,
  pageSizes: [10, 15, 20, 25, 30],
  onUpdatePage: (value: number) => {
    page.value = value;
  },
  onUpdatePageSize: (value: number) => {
    pageSize.value = value;
  }
}));
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <CodeDbSearch v-model:model="searchParams" @search="searchPaginate" />
    <NCard title="数据源" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <TableHeaderOperation
          v-model:columns="columnChecks"
          :disabled-delete="checkedRowKeys.length === 0"
          :loading="loading"
          @add="handleAdd"
          @delete="handleBatchDelete"
          @refresh="refresh"
        />
      </template>
      <NDataTable
        v-model:checked-row-keys="checkedRowKeys"
        :columns="columns"
        :data="data"
        size="small"
        :flex-height="!appStore.isMobile"
        :scroll-x="962"
        :loading="loading"
        remote
        :row-key="row => row.id"
        :pagination="paginationConfig"
        class="sm:h-full"
      />
      <CodeDbDrawer
        v-model:visible="drawerVisible"
        :operate-type="operateType"
        :row-data="editingData"
        @submitted="refresh"
      />
    </NCard>
  </div>
</template>

<style scoped></style>
